package com.cyz.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyz.dao.JobDao;
import com.cyz.dao.StaffDao;
import com.cyz.entity.JobEntity;
import com.cyz.entity.StaffEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
 *
 *
 * @author chenyizhen
 * @email sunlightcs@gmail.com
 * @date 2023-12-18 15:02:10
 */
@RestController
@RequestMapping("user/staff")
public class StaffController {

    @Autowired
    StaffDao staffDao;

    @Autowired
    JobDao jobDao;

    @PostMapping("insert")
    public String insert(String name, String jobName, String tel, String salary){
        StaffEntity staffEntity = new StaffEntity();
        staffEntity.setName(name);
        staffEntity.setTel(tel);
        staffEntity.setSalary(salary);
        staffEntity.setJobId(jobDao.selectOne(new QueryWrapper<JobEntity>().eq("name", jobName)).getId());
        int insert = staffDao.insert(staffEntity);
        return insert == 0 ? "新增失败" : "新增成功";
    }

    @PostMapping("list")
    public List<StaffEntity> list(){
        List<StaffEntity> list = new ArrayList<>();
        for (StaffEntity staffEntity : staffDao.selectList(new QueryWrapper<>())) {
            int jobId = staffEntity.getJobId();
            JobEntity jobEntity = jobDao.selectById(jobId);
            staffEntity.setJobName(jobEntity.getName());
            list.add(staffEntity);
        }
        return list;
    }

    @PostMapping("update")
    public String update(StaffEntity staffEntity){
        StaffEntity entity = staffDao.selectById(staffEntity.getId());
        if (entity == null){
            return "该员工不存在";
        }
        entity.setName(staffEntity.getName());
        entity.setTel(staffEntity.getTel());
        entity.setSalary(staffEntity.getSalary());
        entity.setJobId(jobDao.selectOne(new QueryWrapper<JobEntity>().eq("name", staffEntity.getJobName())).getId());
        int i = staffDao.updateById(entity);
        return i == 0 ? "更新失败" : "更新成功";
    }

    @PostMapping("delete/{id}")
    public String delete(@PathVariable int id){
        int i = staffDao.deleteById(id);
        return i == 0 ? "删除失败" : "删除成功";
    }
}
